from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.responses import RedirectResponse

from app.api.endpoints import analysis, chat, contacts, pua
from app.core.config import settings
from app.services.wechat.hook import wechat_hook

app = FastAPI(
    title=settings.PROJECT_NAME,
    openapi_url=f"{settings.API_V1_STR}/openapi.json"
)

# 设置CORS
if settings.BACKEND_CORS_ORIGINS:
    app.add_middleware(
        CORSMiddleware,
        allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

# 包含API路由
app.include_router(chat.router, prefix=f"{settings.API_V1_STR}/chat", tags=["chat"])
app.include_router(contacts.router, prefix=f"{settings.API_V1_STR}/contacts", tags=["contacts"])
app.include_router(analysis.router, prefix=f"{settings.API_V1_STR}/analysis", tags=["analysis"])
app.include_router(pua.router, prefix=f"{settings.API_V1_STR}/pua", tags=["pua"])


@app.get("/", include_in_schema=False)
async def docs_redirect():
    """
    重定向到API文档
    """
    return RedirectResponse(url="/docs")


@app.on_event("startup")
async def startup_event():
    """
    应用启动时执行
    """
    # 启动微信Hook服务
    wechat_hook.start()


@app.on_event("shutdown")
async def shutdown_event():
    """
    应用关闭时执行
    """
    # 停止微信Hook服务
    wechat_hook.stop()